package com.ayu.shortlink.distribute.mq.consumer;

import cn.hutool.core.collection.CollUtil;
import com.ayu.shortlink.distribute.common.constant.RocketMQConstant;
import com.ayu.shortlink.distribute.common.enums.CouponStatusEnum;
import com.ayu.shortlink.distribute.dao.entity.UserCouponDO;
import com.ayu.shortlink.distribute.dao.mapper.UserCouponMapper;
import com.ayu.shortlink.distribute.mq.basics.base.MessageWrapper;
import com.ayu.shortlink.distribute.mq.basics.event.UserCouponOnTimeCloseEvent;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时将用户优惠券设置为过期
 */
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = RocketMQConstant.TOPIC_USER_COUPON_ON_TIME_CLOSE,
        consumerGroup = RocketMQConstant.GROUP_USER_COUPON_ON_TIME_CLOSE
)
public class UserCouponOnTimeCloseConsumer implements RocketMQListener<MessageWrapper<UserCouponOnTimeCloseEvent>> {
    private final UserCouponMapper userCouponMapper;

    @Override
    public void onMessage(MessageWrapper<UserCouponOnTimeCloseEvent> messageWrapper) {
        UserCouponOnTimeCloseEvent message = messageWrapper.getMessage();
        List<Long> userId = message.getUserId();

        if(CollUtil.isNotEmpty(userId)){
            UserCouponDO couponDO = UserCouponDO.builder().
                    status(CouponStatusEnum.ENDED.getType()).
                    build();
            userId.forEach(id -> {
                LambdaUpdateWrapper<UserCouponDO> updateWrapper = Wrappers.lambdaUpdate(UserCouponDO.class)
                        .eq(UserCouponDO::getUserId, id)
                        .eq(UserCouponDO::getCouponTemplateId, message.getCouponTemplateId());
                userCouponMapper.update(couponDO, updateWrapper);
            });
        }
    }
}
